<template>
  <div class="product-detail">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="商品详情"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <!-- 商品轮播图 -->
    <van-swipe class="product-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(image, index) in productImages" :key="index">
        <img :src="image" class="product-image" />
      </van-swipe-item>
    </van-swipe>
    
    <!-- 商品信息区域 -->
    <div class="product-info">
      <div class="price-section">
        <span class="current-price">¥{{ productData.salePrice || '0.00' }}</span>
        <span class="original-price" v-if="productData.costPrice">¥{{ productData.showPrice }}</span>
      </div>
      
      <div class="product-title">
        <h1>{{ productData.name }}</h1>
        <p class="product-desc">{{ productData.description }}</p>
      </div>
      
      <div class="product-sales">
        <span>销量: {{ productData.sold || 0 }}</span>
        <span>库存: {{ productData.stock || 0 }}</span>
      </div>
    </div>
    
    <!-- 商品规格选择 -->
    <div class="product-specs">
      <van-cell title="选择" is-link @click="showSpecPopup">
        <template #value>
          <span v-if="selectedSpec">{{ selectedSpec }}</span>
          <span v-else>请选择规格</span>
        </template>
      </van-cell>
    </div>
    
    <!-- 商品详情 -->
    <div class="detail-section">
      <van-tabs v-model:active="activeTab">
        <van-tab title="商品详情">
          <div class="detail-content" v-html="productData.detail"></div>
          <div class="detail-images">
            <img v-for="(img, index) in detailImages" :key="index" :src="img" />
          </div>
        </van-tab>
        <van-tab title="规格参数">
          <div class="spec-content">
            <van-cell-group inset>
              <van-cell title="品牌" :value="productData.brand || '暂无'" />
              <van-cell title="型号" :value="productData.model || '暂无'" />
              <van-cell title="产地" :value="productData.origin || '暂无'" />
              <van-cell title="质保期" :value="productData.warranty || '暂无'" />
            </van-cell-group>
          </div>
        </van-tab>
        <van-tab title="用户评价">
          <div class="review-content">
            <van-empty description="暂无评价" v-if="!reviews.length" />
            <van-list v-else>
              <div class="review-item" v-for="(review, index) in reviews" :key="index">
                <div class="review-header">
                  <span class="user-name">{{ review.userName }}</span>
                  <van-rate v-model="review.rating" readonly allow-half />
                </div>
                <div class="review-text">{{ review.content }}</div>
                <div class="review-time">{{ review.createTime }}</div>
              </div>
            </van-list>
          </div>
        </van-tab>
      </van-tabs>
    </div>
    
    <!-- 底部操作栏 -->
    <div class="action-bar">
      <div class="left-btns">
        <van-button icon="home-o" type="default" size="35" @click="goToShop" >主页</van-button>
        <van-button icon="cart-o" type="default" size="35" badge="0" @click="goToCart">购物车</van-button>
      </div>
      <div class="right-btns">
        <van-button type="warning" @click="addToCart">加入购物车</van-button>
        <van-button type="danger" @click="buyNow">立即购买</van-button>
      </div>
    </div>
    
    <!-- 规格选择弹出层 -->
    <van-popup v-model:show="showSpec" position="bottom" round :style="{ height: '40%' }">
      <div class="spec-popup">
        <div class="spec-header">
          <div class="spec-image">
            <img :src="productData.displayImage" alt="商品图片" />
          </div>
          <div class="spec-info">
            <p class="spec-price">¥{{ productData.salePrice || '0.00' }}</p>
            <p class="spec-stock">库存: {{ productData.stock || 0 }}</p>
            <p class="spec-selected">已选: {{ selectedSpec || '请选择' }}</p>
          </div>
          <van-icon name="cross" class="close-icon" @click="showSpec = false" />
        </div>
        
        <div class="spec-options">
          <div class="spec-title">规格</div>
          <div class="spec-list">
            <van-button 
              v-for="spec in specList" 
              :key="spec.id" 
              :type="selectedSpec === spec.name ? 'primary' : 'default'"
              size="small"
              @click="selectSpec(spec)"
            >
              {{ spec.name }}
            </van-button>
          </div>
        </div>
        
        <div class="spec-counter">
          <span>购买数量</span>
          <van-stepper v-model="buyCount" min="1" :max="productData.stock || 1" />
        </div>
        
        <div class="spec-buttons">
          <van-button type="warning" block @click="confirmAddToCart">加入购物车</van-button>
          <van-button type="danger" block @click="confirmBuyNow">立即购买</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getProduct } from '@/api/productManage/product';
import { Toast } from 'vant';

const router = useRouter();
const route = useRoute();
const productId = route.params.id;

const productData = ref({});
const productImages = ref([]);
const detailImages = ref([]);
const loading = ref(false);
const activeTab = ref(0);
const showSpec = ref(false);
const selectedSpec = ref('');
const buyCount = ref(1);
const specList = ref([]);
const reviews = ref([]);

// 获取商品详情
const fetchProductData = async () => {
  loading.value = true;
  try {
    const response = await getProduct(productId);
    if (response.code === 200) {
      productData.value = response.data;
      
      // 处理价格，转换为元
      if (productData.value.salePrice) {
        productData.value.salePrice = productData.value.salePrice / 100;
      }
      
      if (productData.value.costprice) {
        productData.value.costPrice = productData.value.costprice / 100;
      }
      productData.value.showPrice = productData.value.salePrice + 500;
      // 处理图片
      if (productData.value.image) {
        const imageArray = productData.value.image.split(',');
        
        productImages.value = imageArray.map(img => {
          let trimmedImg = img.trim();
          if (trimmedImg.startsWith("/profile/upload")) {
            return "http://www.zyf.com" + trimmedImg.replace("/profile", "");
          }
          return trimmedImg;
        });
        
        // 首图用于展示
        productData.value.displayImage = productImages.value[0];
        detailImages.value = productImages.value.slice(3);
        if (productImages.value.length > 3) {
            productImages.value = productImages.value.slice(0, 3);
        }
      }
      
      // 生成模拟规格数据
      generateSpecList();
    } else {
      Toast.fail('获取商品详情失败');
    }
  } catch (error) {
    console.error('获取商品详情失败', error);
    Toast.fail('获取商品详情失败');
  } finally {
    loading.value = false;
  }
};

// 生成模拟规格数据
const generateSpecList = () => {
  // 这里是模拟数据，实际项目中应该从后端获取
  if (productData.value.type === '手机') {
    specList.value = [
      { id: 1, name: '8GB+128GB 曜金黑' },
      { id: 2, name: '8GB+256GB 曜金黑' },
      { id: 3, name: '12GB+256GB 曜金黑' },
      { id: 4, name: '12GB+512GB 曜金黑' },
      { id: 5, name: '8GB+128GB 雅致白' },
      { id: 6, name: '8GB+256GB 雅致白' },
      { id: 7, name: '12GB+256GB 雅致白' },
      { id: 8, name: '12GB+512GB 雅致白' },
    ];
  } else {
    specList.value = [
      { id: 1, name: '默认' }
    ];
  }
};

// 返回上一页
const onClickLeft = () => {
  router.back();
};

// 显示规格选择弹窗
const showSpecPopup = () => {
  showSpec.value = true;
};

// 选择规格
const selectSpec = (spec) => {
  selectedSpec.value = spec.name;
};

// 加入购物车
const addToCart = () => {
  if (!selectedSpec.value) {
    showSpec.value = true;
  } else {
    confirmAddToCart();
  }
};

// 确认加入购物车
const confirmAddToCart = () => {
  Toast.success('已加入购物车');
  showSpec.value = false;
};

// 立即购买
const buyNow = () => {
  if (!selectedSpec.value) {
    showSpec.value = true;
  } else {
    confirmBuyNow();
  }
};

// 确认立即购买
const confirmBuyNow = () => {
  Toast('购买功能暂未实现');
  showSpec.value = false;
};

// 前往店铺
const goToShop = () => {
  Toast('店铺功能暂未实现');
};

// 前往购物车
const goToCart = () => {
  router.push('/ncwuShop/cart');
};

onMounted(() => {
  fetchProductData();
});
</script>

<style scoped>
.product-detail {
  padding-bottom: 50px;
  background-color: #f5f5f5;
}

.product-swipe {
  height: 410px;
  background-color: #fff;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.product-info {
  padding: 15px;
  background-color: #fff;
  margin-bottom: 10px;
}

.price-section {
  margin-bottom: 10px;
}

.current-price {
  font-size: 24px;
  font-weight: bold;
  color: #f44;
  margin-right: 10px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-title {
  margin-bottom: 10px;
}

.product-title h1 {
  font-size: 18px;
  margin: 0 0 5px 0;
  font-weight: normal;
}

.product-desc {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.product-sales {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #999;
}

.product-specs {
  margin-bottom: 10px;
}

.detail-section {
  background-color: #fff;
  margin-bottom: 60px;
}

.detail-content {
  padding: 15px;
}

.detail-images img {
  width: 100%;
  display: block;
}

.spec-content, .review-content {
  padding: 15px;
}

.review-item {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.review-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.user-name {
  font-size: 14px;
  color: #333;
}

.review-text {
  font-size: 14px;
  margin-bottom: 5px;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #eee;
  z-index: 10;
}

.left-btns {
  display: flex;
  flex: 1;
  justify-content: space-around;
}
.van-button--default{
    border: 0;
}
.right-btns {
  display: flex;
  flex: 2;
}

.right-btns .van-button {
  flex: 1;
  height: 35px;
  border-radius: 20px;
  margin: 0 5px;
}

.spec-popup {
  padding: 15px;
}

.spec-header {
  display: flex;
  position: relative;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.spec-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.spec-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.spec-info {
  flex: 1;
}

.spec-price {
  font-size: 18px;
  color: #f44;
  font-weight: bold;
  margin: 0 0 5px 0;
}

.spec-stock, .spec-selected {
  font-size: 14px;
  color: #999;
  margin: 5px 0;
}

.close-icon {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 20px;
  padding: 10px;
}

.spec-options {
  padding: 15px 0;
}

.spec-title {
  font-size: 16px;
  margin-bottom: 10px;
}

.spec-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.spec-counter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-top: 1px solid #eee;
}

.spec-buttons {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.spec-buttons .van-button {
  flex: 1;
}
</style>